from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import constants, db
from info.models import News, Category, User, Comment, CommentLike
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blue


@news_blue.route('/followed_user', methods=["POST"])
@user_login_data
def followed_user():
    """关注/取消关注用户"""
    # 取自己登录信息
    user=g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    #取新闻用户的id和行为参数
    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 把用户id转化为整数与数据库的格式一致
    try:
        user_id=int(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 根据id查询发表新闻的用户信息
    try:
        news_user= User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据库查询错误")
    if not news_user:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

    # 用户的关注列表添加一个值
    # user.followed.append(news_user)
    # news_user.followers.append(user)

    # 判断是否关注
    if action=="follow":
        if user.id!=user_id:
            if news_user not in user.followed:
                # 用户的关注列表添加一个值
                user.followed.append(news_user)
                # news_user.followers.append(user)
            else:
                return jsonify(errno=RET.DATAEXIST, errmsg="不能重复添加")
        else:
            return jsonify(errno=RET.PARAMERR, errmsg="不能关注自己")
    else:
        if news_user in user.followed:
            user.followed.remove(news_user)

    return jsonify(errno=RET.OK, errmsg="关注成功")


@news_blue.route('/comment_like', methods=['post'])
@user_login_data
def comment_like():
    """
    评论新闻或者回复新闻下指定的评论
    :return:
    """
    # 1.判断用户是否已经登陆
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 2.获取并校验参数
    news_id = request.json.get('news_id')
    comment_id = request.json.get('comment_id')
    action = request.json.get('action')

    if not all([news_id, comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ['add', 'remove']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        comment_id = int(comment_id)
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 3.点赞操作
    try:
        # 找到评论的模型
        comments = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not comments:
        return jsonify(errno=RET.NODATA, errmsg="评论不存在")

    if action == 'add':
        comment_like_model = CommentLike.query.filter(CommentLike.user_id == user.id,
                                                      CommentLike.comment_id == comment_id).first()
        if not comment_like_model:
            # 点赞评论
            comment_like_model = CommentLike()
            comment_like_model.user_id = user.id
            comment_like_model.comment_id = comment_id
            comments.like_count += 1
            db.session.add(comment_like_model)

    else:
        # 取消点赞评论
        comment_like_model = CommentLike.query.filter(CommentLike.user_id == user.id,
                                                      CommentLike.comment_id == comment_id).first()
        if comment_like_model:
            db.session.delete(comment_like_model)
            comments.like_count -= 1
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据库操作失败")

    return jsonify(errno=RET.OK, errmsg="OK")


@news_blue.route('/news_comment', methods=['post'])
@user_login_data
def news_comment():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登陆")
    # 1.获取参数
    news_id = request.json.get('news_id')
    comment_content = request.json.get('comment')
    parent_id = request.json.get('parent_id')
    # 2.判断参数
    if not all([news_id, comment_content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查到新闻数据")
    # 3.初始化模型，添加参数到评论模型
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_content
    if parent_id:
        comment.parent_id = parent_id
    # 添加到数据库
    # 因为return之前需要取到存入数据库的数据，所以在这需要自己提交
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    return jsonify(errno=RET.OK, errmsg="OK", data=comment.to_dict())


@news_blue.route('/news_collect', methods=["POST"])
@user_login_data
def collect_news():
    """
    收藏新闻
    1. 接受参数
    2. 判断参数
    3. 查询新闻，并判断新闻是否存在
    :return:
    """

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 1. 接受参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 2. 判断参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3. 查询新闻，并判断新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")

    # 4. 收藏以及取消收藏
    if action == "cancel_collect":
        # 取消收藏
        if news in user.collection_news:
            user.collection_news.remove(news)
    else:
        # 收藏
        if news not in user.collection_news:
            # 添加到用户的新闻收藏列表
            user.collection_news.append(news)

    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blue.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    """
    新闻详情
    :param news_id:
    :return:
    """
    # from info.utils.common import query_user_data
    # user=query_user_data()

    user = g.user

    # 右侧的新闻排行的逻辑
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 定义一个空的字典列表，里面装的就是字典
    news_dict_li = []
    # 遍历对象列表，将对象的字典添加到字典列表中
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

        # 查询新闻数据
    news = None

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        # 报404错误，404错误统一显示页面后续再处理
        abort(404)

    # 更新新闻的点击次数
    news.clicks += 1

    is_collected = False

    # if 用户已登录：
    #     判断用户是否收藏当前新闻，如果收藏：
    #         is_collected = True

    if user:
        # 判断用户是否收藏当前新闻，如果收藏：
        # collection_news 后面可以不用加all，因为sqlalchemy会在使用的时候去自动加载
        if news in user.collection_news:
            is_collected = True
    comments = []


    # 查询评论数据
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.update_time.desc()).all()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据查询错误")
    # 循环遍历得到评论模型的字典形式数据
    comment_likes_ids = []
    if user:
       try:
           # 需求：在进入详情页时点赞的地方亮起来
           # 1.查询当前新闻下的所有评论（在评论表中查找）,取到所有评论id
           comment_ids = [comment.id for comment in comments]
           # 2. 查询当前评论中被哪些用户点赞
           comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),
                                                    CommentLike.user_id == user.id)
           # 3.取到所有被点赞评论的id
           comment_likes_ids = [comment_like.comment_id for comment_like in comment_likes]
       except Exception as e:
           current_app.logger.error(e)

    comment_dict_li = []
    for comment in comments:
        comment_dict = comment.to_dict()
        comment_dict['is_like'] = False
        #后端添加到是否点赞的属性,控制前端点亮的属性,需要查询当前在当前新闻下的点赞评论
        if comment.id in comment_likes_ids:
            comment_dict['is_like']=True
        comment_dict_li.append(comment_dict)

    # 当前新闻有作者，并且当前登陆用户,以经关注用户(把关注改为True)
    is_followed=False
    if user and news.user:
        if user in news.user.followers:
            is_followed = True
        if news.user in user.followed:
            is_followed = True

    data = {
        "user": user.to_dict() if user else None,
        "news_dict_li": news_dict_li,
        "news": news.to_dict(),
        "is_collected": is_collected,
        "comments": comment_dict_li,
        "is_followed":is_followed
    }

    return render_template("news/detail.html", data=data)
